package com.hqully.smartfumehood.service.impl;

import com.hqully.smartfumehood.entity.User;
import com.hqully.smartfumehood.mapper.RoleMapper;
import com.hqully.smartfumehood.mapper.UserMapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqully.smartfumehood.service.UserService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * <p>
 *     用户服务实现类
 * </p>
 * @author liulingyu
 * @date 2022-05-08 14:39
 * @version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper  userMapper;

    @Autowired
    private RoleMapper roleMapper;


    @Override
    public User findUserByUsername(String username) {

        User user = userMapper.findUserByUsername(username);

        if (user == null){
            return null;
        }

        Integer roleId = roleMapper.findRoleIdByUserId(user.getId());

        String roleName = roleMapper.findNameById(roleId);

        user.setRole(roleName);


        return user;
    }

    @Override
    public String findRoleByUsername(String username) {
        User user = userMapper.findUserByUsername(username);

        Integer roleId = roleMapper.findRoleIdByUserId(user.getId());

        String roleName = roleMapper.findNameById(roleId);

        return roleName;
    }

    @Override
    public Map<String, String> getUserInfo(String username) {

        HashMap<String, String> userInfoMap = new HashMap<>();

        Integer roleId = roleMapper.findRoleIdByUserId(username);

        String roleName = roleMapper.findNameById(roleId);

        userInfoMap.put("role",roleName);

        return userInfoMap;
    }

    @Override
    public Long findUnitByUsername(String username) {
        return userMapper.findUnitByUsername(username);
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public int register(User user) {

        String password = user.getPassword();

        String salt = new SecureRandomNumberGenerator().nextBytes().toString();

        String algorithmName = "md5";

        int times = 2;

        String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString();

        user.setPassword(encodedPassword);

        user.setSalt(salt);

        addUser(user);
        return 0;
    }
}
